package study.alibaba.sentinel.support.sentinel;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.SentinelWebInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import study.alibaba.sentinel.support.exception.GlobalBlockExceptionHandler;

@Slf4j
@Configuration
public class SentinelWebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //
        com.alibaba.csp.sentinel.adapter.spring.webmvc.config.SentinelWebMvcConfig config =
                new com.alibaba.csp.sentinel.adapter.spring.webmvc.config.SentinelWebMvcConfig();
        //指定资源名是否包含请求方法，如 POST:/api/getUserInfo
        config.setHttpMethodSpecify(false);
        //默认使用统一 Web 上下文，如果希望支持链路关系的流控策略则应该设置为 false
        config.setWebContextUnify(true);
        //统一的 BlockException 处理
        //FlowException（BlockException） 会被 JVM 的 UndeclaredThrowableException 包裹一层，某种原因并不能捕获到异常
        config.setBlockExceptionHandler(new GlobalBlockExceptionHandler());
        // 用来标识来源 可针对性的对特定客户端的请求进行流控   limitApp
        //webConfig.setOriginParser(request -> request.getHeader("X-Client"));
        //webConfig.setOriginParser(request -> request.getParameter("app"));
        //对原始的URL进行处理，比如去掉锚点之类的    /foo/bar?a=3#title  ->   /foo/bar?a=3
        //webConfig.setUrlCleaner( );

        //
        SentinelWebInterceptor interceptor = new SentinelWebInterceptor(config);

        //
        registry.addInterceptor(interceptor)
                .addPathPatterns("/**");
    }
}
